<template>
  <div class="data-import">
    <el-dialog 
      v-model="visible" 
      title="导入数据" 
      width="600px"
      @close="handleClose">
      
      <el-tabs v-model="activeTab" type="border-card">
        <!-- CSV文件导入 -->
        <el-tab-pane label="CSV文件" name="csv">
          <div class="import-section">
            <el-upload
              ref="uploadRef"
              :auto-upload="false"
              :show-file-list="false"
              accept=".csv"
              @change="handleFileChange">
              <el-button type="primary">
                <el-icon><Upload /></el-icon>
                选择CSV文件
              </el-button>
            </el-upload>
            
            <div v-if="csvData.length" class="preview-section">
              <h4>数据预览 (前5行)</h4>
              <el-table :data="csvData.slice(0, 5)" border size="small">
                <el-table-column 
                  v-for="column in csvColumns"
                  :key="column"
                  :prop="column"
                  :label="column"
                  show-overflow-tooltip />
              </el-table>
              
              <div class="field-mapping">
                <h4>字段映射</h4>
                <el-form label-width="100px">
                  <el-form-item 
                    v-for="column in csvColumns"
                    :key="column"
                    :label="column">
                    <el-select 
                      v-model="fieldMapping[column]"
                      placeholder="选择字段类型">
                      <el-option label="维度(文本)" value="dimension" />
                      <el-option label="度量值(数值)" value="measure" />
                      <el-option label="日期" value="date" />
                      <el-option label="忽略" value="ignore" />
                    </el-select>
                  </el-form-item>
                </el-form>
              </div>
            </div>
          </div>
        </el-tab-pane>
        
        <!-- JSON数据导入 -->
        <el-tab-pane label="JSON数据" name="json">
          <div class="import-section">
            <el-input
              v-model="jsonInput"
              type="textarea"
              :rows="10"
              placeholder="请输入JSON格式的数据，例如：
[
  {&quot;name&quot;: &quot;张三&quot;, &quot;age&quot;: 25, &quot;department&quot;: &quot;技术部&quot;},
  {&quot;name&quot;: &quot;李四&quot;, &quot;age&quot;: 30, &quot;department&quot;: &quot;销售部&quot;}
]" />
            
            <div v-if="jsonData.length" class="preview-section">
              <h4>数据预览</h4>
              <el-table :data="jsonData.slice(0, 5)" border size="small">
                <el-table-column 
                  v-for="column in jsonColumns"
                  :key="column"
                  :prop="column"
                  :label="column"
                  show-overflow-tooltip />
              </el-table>
            </div>
          </div>
        </el-tab-pane>
        
        <!-- 数据库连接 -->
        <el-tab-pane label="数据库" name="database">
          <div class="import-section">
            <el-form :model="dbConfig" label-width="100px">
              <el-form-item label="数据库类型">
                <el-select v-model="dbConfig.type">
                  <el-option label="MySQL" value="mysql" />
                  <el-option label="PostgreSQL" value="postgresql" />
                  <el-option label="SQLite" value="sqlite" />
                </el-select>
              </el-form-item>
              <el-form-item label="主机地址">
                <el-input v-model="dbConfig.host" placeholder="localhost" />
              </el-form-item>
              <el-form-item label="端口">
                <el-input v-model="dbConfig.port" placeholder="3306" />
              </el-form-item>
              <el-form-item label="数据库名">
                <el-input v-model="dbConfig.database" />
              </el-form-item>
              <el-form-item label="用户名">
                <el-input v-model="dbConfig.username" />
              </el-form-item>
              <el-form-item label="密码">
                <el-input v-model="dbConfig.password" type="password" />
              </el-form-item>
              <el-form-item label="SQL查询">
                <el-input
                  v-model="dbConfig.query"
                  type="textarea"
                  :rows="4"
                  placeholder="SELECT * FROM table_name" />
              </el-form-item>
            </el-form>
            
            <el-button type="primary" @click="testConnection">测试连接</el-button>
          </div>
        </el-tab-pane>
      </el-tabs>
      
      <template #footer>
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleImport" :disabled="!canImport">
          导入数据
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { useTableStore } from '../stores/tableStore'
import { Upload } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:modelValue', 'imported'])

const tableStore = useTableStore()

// 响应式数据
const visible = ref(props.modelValue)
const activeTab = ref('csv')
const csvData = ref([])
const csvColumns = ref([])
const fieldMapping = ref({})
const jsonInput = ref('')
const jsonData = ref([])
const jsonColumns = ref([])
const dbConfig = ref({
  type: 'mysql',
  host: 'localhost',
  port: '3306',
  database: '',
  username: '',
  password: '',
  query: ''
})

// 计算属性
const canImport = computed(() => {
  switch (activeTab.value) {
    case 'csv':
      return csvData.value.length > 0
    case 'json':
      return jsonData.value.length > 0
    case 'database':
      return dbConfig.value.database && dbConfig.value.query
    default:
      return false
  }
})

// 监听器
watch(() => props.modelValue, (newVal) => {
  visible.value = newVal
})

watch(visible, (newVal) => {
  emit('update:modelValue', newVal)
})

watch(jsonInput, (newVal) => {
  if (newVal) {
    try {
      const parsed = JSON.parse(newVal)
      if (Array.isArray(parsed) && parsed.length > 0) {
        jsonData.value = parsed
        jsonColumns.value = Object.keys(parsed[0])
      }
    } catch (error) {
      jsonData.value = []
      jsonColumns.value = []
    }
  }
})

// 方法
const handleFileChange = (file) => {
  const reader = new FileReader()
  reader.onload = (e) => {
    const csv = e.target.result
    parseCSV(csv)
  }
  reader.readAsText(file.raw)
}

const parseCSV = (csv) => {
  const lines = csv.split('\n').filter(line => line.trim())
  if (lines.length < 2) return
  
  const headers = lines[0].split(',').map(h => h.trim().replace(/"/g, ''))
  csvColumns.value = headers
  
  csvData.value = lines.slice(1).map(line => {
    const values = line.split(',').map(v => v.trim().replace(/"/g, ''))
    const row = {}
    headers.forEach((header, index) => {
      row[header] = values[index] || ''
    })
    return row
  })
  
  // 初始化字段映射
  fieldMapping.value = {}
  headers.forEach(header => {
    // 自动推断字段类型
    const sampleValue = csvData.value[0][header]
    if (!isNaN(sampleValue) && sampleValue !== '') {
      fieldMapping.value[header] = 'measure'
    } else if (isDateString(sampleValue)) {
      fieldMapping.value[header] = 'date'
    } else {
      fieldMapping.value[header] = 'dimension'
    }
  })
}

const isDateString = (str) => {
  return !isNaN(Date.parse(str)) && isNaN(Number(str))
}

const testConnection = () => {
  // 这里应该实现真实的数据库连接测试
  ElMessage.info('数据库连接功能需要后端支持')
}

const handleImport = () => {
  let data = []
  let fields = []
  
  switch (activeTab.value) {
    case 'csv':
      data = csvData.value
      fields = generateFields(csvColumns.value, fieldMapping.value)
      break
    case 'json':
      data = jsonData.value
      fields = generateFieldsFromData(jsonData.value)
      break
    case 'database':
      ElMessage.info('数据库导入功能需要后端支持')
      return
  }
  
  if (data.length > 0) {
    // 创建新的数据源
    const newDataSource = {
      id: `imported_${Date.now()}`,
      name: `导入数据_${new Date().toLocaleString()}`,
      type: 'imported',
      data: data
    }
    
    // 更新store
    tableStore.dataSources.push(newDataSource)
    tableStore.currentDataSource = newDataSource
    tableStore.fields = fields
    
    ElMessage.success(`成功导入 ${data.length} 条数据`)
    emit('imported', { dataSource: newDataSource, fields })
    handleClose()
  }
}

const generateFields = (columns, mapping) => {
  return columns.map(column => {
    const type = mapping[column]
    return {
      id: column.toLowerCase().replace(/\s+/g, '_'),
      name: column,
      type: type === 'measure' ? 'number' : (type === 'date' ? 'date' : 'string'),
      category: type === 'measure' ? '度量值' : '维度',
      dataType: type === 'measure' ? 'number' : (type === 'date' ? 'date' : 'text')
    }
  }).filter(field => mapping[field.name] !== 'ignore')
}

const generateFieldsFromData = (data) => {
  if (!data.length) return []
  
  const sample = data[0]
  return Object.keys(sample).map(key => {
    const value = sample[key]
    const isNumber = !isNaN(value) && value !== ''
    const isDate = isDateString(value)
    
    return {
      id: key.toLowerCase().replace(/\s+/g, '_'),
      name: key,
      type: isNumber ? 'number' : (isDate ? 'date' : 'string'),
      category: isNumber ? '度量值' : '维度',
      dataType: isNumber ? 'number' : (isDate ? 'date' : 'text')
    }
  })
}

const handleClose = () => {
  visible.value = false
  // 重置数据
  csvData.value = []
  csvColumns.value = []
  fieldMapping.value = {}
  jsonInput.value = ''
  jsonData.value = []
  jsonColumns.value = []
}
</script>

<style scoped>
.import-section {
  padding: 20px 0;
}

.preview-section {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #e4e7ed;
}

.preview-section h4 {
  margin-bottom: 12px;
  color: #303133;
}

.field-mapping {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #e4e7ed;
}

.field-mapping h4 {
  margin-bottom: 16px;
  color: #303133;
}

.el-upload {
  width: 100%;
}

.el-textarea {
  margin-bottom: 16px;
}
</style>

